Thread: [Help] malloc();

  1. #1
    Registered User
    Join Date
    Feb 2017
    Posts
    12

    [Help] malloc();

    I'm trying to understand malloc(); and reading some examples but I found some difficult, I didn't get it yet, is there any simple way to understand how it works and what is other functions I need to know with malloc(); to understand the big image of 'em.

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Generally, people want one of two things from malloc().

    Allocating a single object on the heap: this is important for data structures where you have a tree or list node and want to link pointers together.
    Code:
    node *p= malloc(sizeof *p);
    if (p != NULL) {
       p->data = getValue();
       // fill the rest of the node 
    }
    Simulating an array with pointer: other times you might need an array structure where the size is determined at run time, the size is flexible, or both.
    Code:
    object *arr;
    int size;
    printf("Enter the size of the array: ");
    size = getValue();
    arr = malloc(size * sizeof arr[0]);
    if (arr == NULL) {
       fprintf(stderr, "array could not be allocated\n");
       return 1;
    }
    // use arr
    The multiplication step here is all you need to really do to ask for enough bytes for the array.

    I haven't talked about sizeof yet, but all that the operator does is give the size of its operand in bytes. The argument can be any data type. If you say sizeof(int), it gives you the size of an int.

    Feel free to use sizeof like that your whole life. It's not wrong, but some people find it error prone. After all, if the type of a variable changes at some stage of the development life-cycle, now you have to change the variable in at least two places. There is an easier way to use sizeof, which is also the way I showed. If you can dereference your pointer, and make that your operand to sizeof, it will never be wrong, even if the type changes. So, again, if the type changes at some stage, you have to change the variable in less places.

    Additionally:

    The if statements matter: when malloc() fails, it will return a NULL pointer. Check for that and respond accordingly, always. You cannot use NULL pointers.

    Free your memory when your done.
    Code:
    free(p);
    p = NULL;
    free(arr);
    arr = NULL;
    Now with this you understand the two most important reasons why people call malloc() and how to successfully call it in those cases. Once you have this under your belt, read about dynamic 2D arrays, and then you'll be as equipped as anyone. At the same time, please don't consider this post exhaustive, and consult other references you may have found again. As a warning, knowing how and why to call malloc() does not mean that you've programmed correctly. Memory leaks can still happen and it's the programmer's job to look for any of them, either with experience (spotting problems by looking at code) or tools (like valgrind), or ideally a combination of the two, and fix them.

    malloc(3): allocate/free dynamic memory - Linux man page
    Last edited by whiteflags; 03-04-2017 at 02:46 PM. Reason: It's correct now, I promise.

  3. #3
    Registered User
    Join Date
    May 2012
    Posts
    505

    Post

    Quote Originally Posted by ahmedcrow View Post
    I'm trying to understand malloc(); and reading some examples but I found some difficult, I didn't get it yet, is there any simple way to understand how it works and what is other functions I need to know with malloc(); to understand the big image of 'em.
    malloc is used in two situations; firstly when you don't know how big an array needs to be until runtime, and secondly when you want to create a semi-permanent copy of an object that exists for a long time.

    You can quite easily write your own mymalloc / myfree allocating from a static memory buffer you declare - see my book for an example of who to do this.

    Essentially, if we are writing a payroll, we are unlikely to know how many employees the client has when we write the program. So we can't say
    Code:
    #define NEMPLOYEES 107
    Employee[NEMPLOYEEES] employeelist;
    We must say

    Code:
    int Nemployees = readnumberofemployees();
    Employee *employeelist = malloc(Nemployees * sizeof(Employee));
    That's essentially all malloc is.
    I'm the author of MiniBasic: How to write a script interpreter and Basic Algorithms
    Visit my website for lots of associated C programming resources.
    https://github.com/MalcolmMcLean


  4. #4
    Registered User
    Join Date
    Feb 2017
    Posts
    12
    Quote Originally Posted by Malcolm McLean View Post
    You can quite easily write your own mymalloc / myfree allocating from a static memory buffer you declare - see my book for an example of who to do this.
    Where can I found the book you referred to ?

  5. #5
    Registered User
    Join Date
    Feb 2017
    Posts
    12
    Quote Originally Posted by whiteflags View Post
    Now with this you understand the two most important reasons why people call malloc() and how to successfully call it in those cases. Once you have this under your belt, read about dynamic 2D arrays, and then you'll be as equipped as anyone. At the same time, please don't consider this post exhaustive, and consult other references you may have found again. As a warning, knowing how and why to call malloc() does not mean that you've programmed correctly. Memory leaks can still happen and it's the programmer's job to look for any of them, either with experience (spotting problems by looking at code) or tools (like valgrind), or ideally a combination of the two, and fix them.
    Thank you, good effort from you.

  6. #6
    Registered User
    Join Date
    May 2012
    Posts
    505
    Quote Originally Posted by ahmedcrow View Post
    Where can I found the book you referred to ?
    You can download it from here

    Basic Algorithms by Malcolm McLean (eBook) - Lulu
    Last edited by Malcolm McLean; 03-06-2017 at 05:18 AM.
    I'm the author of MiniBasic: How to write a script interpreter and Basic Algorithms
    Visit my website for lots of associated C programming resources.
    https://github.com/MalcolmMcLean


  7. #7
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    ^This book^ is a piece of garbage. There are many good books on this subject. Only an idiot would pick one suggested by the (totally unqualified) person who wrote it. Hopefully you're not so stupid as to waste your time on it.

    books on algorithms

    (Remember to read reviews.)

  8. #8
    Registered User
    Join Date
    Feb 2017
    Posts
    12
    Quote Originally Posted by algorism View Post
    ^This book^ is a piece of garbage. There are many good books on this subject. Only an idiot would pick one suggested by the (totally unqualified) person who wrote it. Hopefully you're not so stupid as to waste your time on it.

    books on algorithms

    (Remember to read reviews.)
    Give him a chance, it's not wrong if he is trying to learn people with his own experience, may be he has lot experience, may be he has few, he is doing the best he can, anyway I'm a poor man, I can't buy books from net, I learn from sources I can have with the web.

    It's nice books too you showed, thanks

  9. #9
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Maybe if he gave review copies I would be able to form a good opinion on his book. Until then, I don't know his background and can't recommend it either. It may as well be a book written on modern astronomy by Ptolemy.
    Last edited by whiteflags; 03-06-2017 at 01:17 PM.

  10. #10
    Registered User
    Join Date
    Feb 2017
    Posts
    12
    I think "C the complete reference 4th edition by Herbert Schildt" is good American book and it talked about malloc(); and some algorithms, I didn't read it yet but I saw its contents.

  11. #11
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    You might want to look for the books in this thread. C Book Recommendations They are stuff that other members here have read. I'm sure they all talk about malloc() and other more important topics, frankly.

  12. #12
    Registered User
    Join Date
    Feb 2017
    Posts
    12
    I'll take a look to that books, ok.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Here we go again: when to use Malloc and when not?
    By django in forum C Programming
    Replies: 52
    Last Post: 08-09-2011, 07:56 AM
  2. Replies: 7
    Last Post: 05-19-2010, 02:12 AM
  3. Replies: 7
    Last Post: 10-01-2008, 07:45 PM
  4. Using malloc
    By ulillillia in forum C Programming
    Replies: 34
    Last Post: 02-20-2008, 06:41 PM
  5. When and when not to use malloc()?
    By John.H in forum C Programming
    Replies: 5
    Last Post: 03-24-2003, 06:00 PM

Tags for this Thread